package com.kefu.call.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kefu.call.http.client.CtiClient;
import com.kefu.call.mapper.CallDialplanAppMapper;
import com.kefu.call.mapper.CallDialplanMapper;
import com.kefu.call.mapper.IvrComMapper;
import com.kefu.call.model.*;
import com.kefu.call.vo.CallIvrComInsertVo;
import com.kefu.call.vo.CallIvrComUpdateVo;
import com.kefu.common.context.KefuContext;
import com.kefu.common.exception.BusinessException;
import com.kefu.common.service.AbstractKefuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class CallIvrComService extends AbstractKefuService<IvrCom> {
    @Autowired
    CtiClient ctiClient;
    @Resource
    private CallDialplanMapper callDialplanMapper;
    @Resource
    private CallDialplanAppMapper callDialplanAppMapper;

    public List<IvrComVo> queryList(){
        List<IvrCom> list = lambdaQuery().eq(IvrCom::getFoid, KefuContext.getTid())
                .orderByDesc(IvrCom::getUpdateTime).list();
        return Convert.toList(IvrComVo.class,list);
    }

    public void add(CallIvrComInsertVo insertVo){
        IvrCom ivrCom = BeanUtil.toBean(insertVo, IvrCom.class);
        ivrCom.setFoid(KefuContext.getTid());
        ivrCom.setUpdateTime(System.currentTimeMillis());
        ivrCom.setJsonstr("{\"name\":\"\",\"nodeList\":[],\"lineList\":[]}");
        save(ivrCom);
        updateDialplan(ivrCom.getOid(),insertVo.getInnumber());

    }

    public void update(CallIvrComUpdateVo updateVo){
        IvrCom ivrCom = BeanUtil.toBean(updateVo, IvrCom.class);
        ivrCom.setUpdateTime(System.currentTimeMillis());
        updateById(ivrCom);
        updateDialplan(ivrCom.getOid(),updateVo.getInnumber());
    }

    void updateDialplan(String oid ,String numbers){
        if(StrUtil.isNotBlank(numbers)){
            for (String number : numbers.split(",")) {
                CallDialplan dialplan = callDialplanMapper.selectOne(Wrappers.lambdaQuery(CallDialplan.class)
                        .eq(CallDialplan::getExpression,number).last("limit 1"));
                if(dialplan!=null){
                    callDialplanAppMapper.update(null,Wrappers.lambdaUpdate(CallDialplanApp.class)
                            .set(CallDialplanApp::getData,"ivr.lua " + KefuContext.getTid() + " " + oid)
                            .eq(CallDialplanApp::getDialplan,dialplan.getFOid())
                            .like(CallDialplanApp::getData,"ivr.lua"));
                }
            }
            ctiClient.reloadFsCache("dialplan");
        }
    }

}
